package com.ubi.core.swagger;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.mangofactory.swagger.models.dto.ApiListing;
import com.mangofactory.swagger.models.dto.Parameter;

/**
 * @author leiyi
 * @date 2016-04-27 10:56
 * @summary:SwaggerJacksonMessageConverter
 * swagger的APIListing是返回给前端页面展示的
 * 默认没有驼峰转下划线，如果使用全局的驼峰转下划线处理，前端页面会报错
 * 所以转化的时候需要忽略这个类
 */
public class SwaggerJacksonConvert extends LowerCaseWithUnderscoresStrategy {

    @Override
    public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        if (shouldIgnore(method)) {
            return defaultName;
        }
        return super.nameForGetterMethod(config, method, defaultName);
    }

    @Override
    public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        if (shouldIgnore(method)) {
            return defaultName;
        }
        return super.nameForSetterMethod(config, method, defaultName);
    }

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        if (shouldIgnore(field)) {
            return defaultName;
        }
        return super.nameForField(config, field, defaultName);
    }

    private boolean shouldIgnore(AnnotatedMethod annotatedMethod) {
        if (annotatedMethod != null) {
            Class<?> clazz = annotatedMethod.getDeclaringClass();
            if (clazz == ApiListing.class || clazz == Parameter.class) {
                return true;
            }
        }
        return false;
    }

    private boolean shouldIgnore(AnnotatedField annotatedField) {
        if (annotatedField != null) {
            Class<?> clazz = annotatedField.getDeclaringClass();
            if (clazz == ApiListing.class || clazz == Parameter.class) {
                return true;
            }
        }
        return false;
    }
}
